package com.bw.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bw.domain.User;
import com.bw.service.UserService;
import com.bw.utils.common.JWTUtils;
import com.bw.utils.common.Result;
import com.sun.javafx.tk.TKClipboard;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisHash;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

@RequestMapping("auth")
@RestController
public class AuthController {
    @Autowired
    UserService userService;
    @Autowired
    RedisTemplate redisTemplate;

    @RequestMapping("login")
    public Result login(@RequestBody User user){
        String dbCode = (String) redisTemplate.opsForValue().get(user.getUuid());
        if(!dbCode.equals(user.getCode())){
            return  Result.fail("验证码不对");
        }
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername,user.getUsername());
        User dbUser = userService.getOne(wrapper);
        if(dbUser==null){
            return  Result.fail("账户不存在");
        }
        if(!dbUser.getPassword().equals(user.getPassword())){
            return Result.fail("密码不对");
        }
        String token = JWTUtils.createToken(dbUser.getId(), 5);
        return Result.success(token);
    }

    @RequestMapping("getCode")
    public void getCode(String uuid, HttpServletResponse response) throws IOException {
        CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(200, 100, 4, 20);
        captcha.write(response.getOutputStream());
        redisTemplate.opsForValue().set(uuid,captcha.getCode(),5, TimeUnit.MINUTES);
    }

}
